package com.wquick.base.utils.asyncTask

import android.os.Handler
import android.os.Looper
import com.wquick.base.utils.tryFinally
import java.util.concurrent.CountDownLatch

object ThreadUtils {

    private val uiHandler by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) { Handler(Looper.getMainLooper()) }

    /** 判断是否是主线程 */
    val isUiThread: Boolean
        get() = Looper.getMainLooper() == Looper.myLooper()

    /** 断言当前线程是否是主线程 */
    fun assertUiThread() {
        if (!isUiThread) throw java.lang.IllegalStateException("当前不是主线程")
    }

    /** 在主线程运行一个任务 */
    fun runTaskMainThread(task: Runnable) {
        if (isUiThread) {
            task.run()
            return
        }
        postTaskMainThread(task)
    }

    /** post一个任务到主线程 */
    fun postTaskMainThread(task: Runnable) {
        uiHandler.post(task)
    }

    /** post一个延迟任务到主线程 */
    fun postTaskMainThreadDelay(delayMillis: Long, task: Runnable) {
        uiHandler.postDelayed(task, delayMillis)
    }

    /** post一个任务到IO线程 */
    fun postTaskIoThread(task: Runnable) {
        AsyncTaskExecutors.UNBOUNDED.execute(task)
    }

    /** 取消一个主线程任务 */
    fun removeUiTask(task: Runnable) {
        uiHandler.removeCallbacks(task)
    }

    fun runOnUiTaskSync(task: Runnable) {
        if (isUiThread) {
            task.run()
            return
        }
        val sync = CountDownLatch(1)
        runTaskMainThread { tryFinally({ task.run() }, { sync.countDown() }) }
        try {
            sync.await()
        } catch (e: InterruptedException) {
            throw AssertionError(e)
        }
    }
}